package LessonPrac;

import com.lovo.netCRM.component.LovoButton;
import com.lovo.netCRM.component.LovoFileChooser;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class MyJFrame extends JFrame {
    //文件选择器
    private LovoFileChooser fileChooser = new LovoFileChooser(this);

    public MyJFrame(){
        this.setLayout(null);
        this.init();

        this.setSize(600,400);
        this.setVisible(true);
        this.setDefaultCloseOperation(3);
        this.setLocationRelativeTo(null);
    }

    private void init(){
        //设置组件的位置和大小
        this.fileChooser.setBounds(50,50,200,260);

        LovoButton addButton = new LovoButton("保存",300,100,this);
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                save();
            }
        });
    }

    private void save(){
        //得到选择文件的路径
        String str = fileChooser.getFilePath();
//        System.out.println(str);

        InputStream in = null;
        OutputStream out = null;

        //以时间毫秒数构建输出文件名，避免文件因重名而覆盖
        String outFile = System.currentTimeMillis() + str.substring(str.lastIndexOf("."));
        try {
            int len = 0;
            byte[] byteArray = new byte[1024];

            in = new FileInputStream(str);
            out = new FileOutputStream("Class9_15/face/"+outFile);

            while ((len=in.read(byteArray))!=-1){
                out.write(byteArray,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                out.close();
                in.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new MyJFrame();
    }
}
